package service;

import model.Hobby;
import model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import repository.HobbyRepository;

import java.util.ArrayList;
import java.util.List;

@Service
public class HobbyService {

    protected final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private HobbyRepository hobbyRepository;

    public void saveHobbies(List<Hobby> hobbies, User user) {
        for(Hobby hobby : hobbies) {
            hobby.setUser(user);
            hobbyRepository.save(hobby);
        }
    }

    public void updateHobbies(List<Hobby> hobbies, User user) {

        if ((hobbies != null) && (user.getId() > 0)) {

            List<Hobby> oldHobbies = hobbyRepository.getHobbiesByUser(user.getId());

            log.info("oldHobbies count : "+oldHobbies.size());
            log.info("hobbies count : "+hobbies.size());

            if (oldHobbies == null)
                oldHobbies = new ArrayList<Hobby>();

            boolean hobbyExists;

            // saving and updating hobbies
            for(Hobby h : hobbies) {

                hobbyExists = false;

                for (Hobby oldH : oldHobbies) {

                    if (h.getId() == oldH.getId()) {

                        h.setUser(user);
                        hobbyRepository.save(h);
                        log.info("updating hobby : "+h.getId());

                        hobbyExists = true;
                        break;
                    }
                }

                if (!hobbyExists) {
                    h.setUser(user);
                    hobbyRepository.save(h);
                    log.info("save hobby : "+h.getId());
                }
            }

            // deleting hobbies
            for(Hobby oldH : oldHobbies) {

                hobbyExists = false;

                for (Hobby h : hobbies) {

                    if (h.getId() == oldH.getId()) {

                        hobbyExists = true;
                        break;
                    }
                }

                if (!hobbyExists) {
                    hobbyRepository.delete(oldH);
                    log.info("delete hobby : "+oldH.getId());
                }
            }
        }
    }
}
